export class Socket {
  constructor({ url, onmessage }) {
    this.socket = new WebSocket(url)
    this.onmessage = onmessage
    this.close = this.close
    this.readyState = 3
    this.timeoutId = 0
    this.connectWs()
  }
  createdSocket() {
    this.socket.onerror = (event) => {
      this.readyState = this.socket.readyState
      this.reconnection()
      console.log(event, '连接出错')
    }
    this.socket.onopen = (event) => {
      this.readyState = this.socket.readyState
      // 防止websocket 超时
      this.keepAlive()
      console.log('前端 open', event)
    }
    this.socket.onmessage = this.onmessage
    this.socket.onclose = (event) => {
      this.readyState = this.socket.readyState
      this.cancelKeepAlive()
      console.log('close', event)
    }
  }
  // 重连
  reconnection() {
    if (this.readyState === 1) return
    clearTimeout(this.timeId)
    this.timeId = setTimeout(() => {
      this.createdSocket()
    }, 2000)
  }
  connectWs() {
    this.createdSocket()
  }
  close() {
    console.log('关闭')
    this.socket.close(1000)
  }
  keepAlive() {
    const timeout = 4000

    if (this.readyState === this.socket.readyState) {
      this.socket.send('')
    }
    this.timeoutId = setTimeout(() => {
      this.keepAlive()
    }, timeout)
  }
  cancelKeepAlive() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId)
    }
  }
}
